package com.ken.android.music.service;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.browse.MediaBrowser;
import android.media.session.MediaSession;
import android.media.session.PlaybackState;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.service.media.MediaBrowserService;
import android.util.Log;

import com.ken.android.music.consts.Config;
import com.ken.android.music.db.MusicDao;
import com.ken.android.music.model.MusicBean;
import com.ken.android.music.player.MusicPlayer;
import com.ken.android.music.view.MyApplication;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


/**
 * Created by axnshy on 16/4/19.
 */
public class PlayerService extends MediaBrowserService implements MusicPlayer {
    private static final String TAG = PlayerService.class.getSimpleName();
    public static int PlayerState = 1;
    public static int MediaPlayer_PLAY = 2;
    public static int MediaPlayer_PAUSE = 1;


    public int repeatTag = 0;
    public int shuffleTag = 0;
    private ArrayList<MusicBean> mList;

    private MediaSession mMediaSession;

    private MediaPlayer mPlayer;

    private static final String MY_MEDIA_ROOT_ID = "media_root_id";
    private static final String MY_EMPTY_MEDIA_ROOT_ID = "empty_root_id";

    private PlaybackState.Builder mStateBuilder;
    public static final int MSG_SETMUSICURI = 1;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
//                case 1: {
//                    mList = (ArrayList<MusicBean>) msg.obj;
//                    currentMusic = mList.get(0);
//                    Log.e("TAG", "List 以获取");
//                    mPlayer = createMediaPlayer();
//                    if (mPlayer != null) {
//                        mPlayer.setOnPreparedListener(PlayerService.this);
//                    }
//                    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//                    break;
//                }
//                case 0:
//                    Log.e("TAG", " --------------- currentMusic -------------" + currentMusic);
//                    mObservable.notifyChanged(currentMusic);
//                    break;

                case MSG_SETMUSICURI:
                    setMusicUri((Uri) msg.obj);

            }
        }
    };

    private void setMusicUri(Uri uri) {
        release();
        mPlayer = createMediaPlayer();
        try {
            if (repeatTag == 0)
                mPlayer.setLooping(false);
            if (repeatTag == 1)
                mPlayer.setLooping(true);
            mPlayer.setDataSource(MyApplication.getApplication(),uri);
            mPlayer.setOnPreparedListener(preparedListener);
            mPlayer.setOnCompletionListener(completionListener);
            mPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * 当前播放资源的绝对路径
     * */
    private String uri;

    /*
     * 当前播放资源的Id
     *
     * */

    public MusicBean currentMusic;


    //private Context context;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(LOG_TAG, "onBind");
        return mBinder;
    }

    @Nullable
    @Override
    public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid, @Nullable Bundle rootHints) {
        return new BrowserRoot(this.getClass().getSimpleName(),rootHints);
    }

    @Override
    public void onLoadChildren(@NonNull String parentId, @NonNull Result<List<MediaBrowser.MediaItem>> result) {

    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(LOG_TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    public static final String LOG_TAG = "LOG_TAG";

    private MyBinder mBinder = new MyBinder();

    private class MyBinder extends Binder {

        public PlayerService getService() {
            return PlayerService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mMediaSession = new MediaSession(this,"goodmusic");
        mStateBuilder = new PlaybackState.Builder();
        mStateBuilder.setActions(getAvailableActions());

        // Enable callbacks from MediaButtons and TransportControls
        mMediaSession.setFlags(
                MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
                        MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mMediaSession.setPlaybackState(mStateBuilder.build());
        mMediaSession.setCallback(new MediaSession.Callback() {
            @Override
            public void onPlay() {
                super.onPlay();
            }

            @Override
            public void onPause() {
                super.onPause();
            }

            @Override
            public void onPrepare() {
                super.onPrepare();
            }

            @Override
            public void onPlayFromUri(Uri uri, Bundle extras) {
                super.onPlayFromUri(uri, extras);
                handler.sendMessage(Message.obtain(handler,MSG_SETMUSICURI,uri));
            }
        });
        setSessionToken(mMediaSession.getSessionToken());
    }

    private long getAvailableActions(){
        return PlaybackState.ACTION_PLAY|
                PlaybackState.ACTION_PAUSE|
                PlaybackState.ACTION_FAST_FORWARD|
                PlaybackState.ACTION_REWIND|
                PlaybackState.ACTION_SEEK_TO|
                PlaybackState.ACTION_SKIP_TO_NEXT|
                PlaybackState.ACTION_SKIP_TO_PREVIOUS;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //super.onStartCommand();
        //初始化media player
        initEvent();
        return START_STICKY;
    }

    private void initEvent() {
        //getList(PlayerService.this);
    }

    private ArrayList<MusicBean> getMyList() {
        return mList;
    }

    private MusicBean getPreviousMusic() {
        int location = getMyList().indexOf(currentMusic);
        if (location == 0) {
            return getMyList().get(getMyList().size() - 1);
        } else
            return getMyList().get(location - 1);
    }

    public MusicBean getNextMusic() {
        int location = getMyList().indexOf(currentMusic);
        if (location == getMyList().size() - 1) {
            return getMyList().get(0);
        } else
            return getMyList().get(location + 1);
    }

    public int getPlayerState() {
        if (PlayerState > 0)
            return PlayerState;
        return -1;
    }

    public void setPlayerState(int state) {
        PlayerState = state;
    }


    public void setPlayerList(ArrayList<MusicBean> list) {
        this.mList = list;
        currentMusic = mList.get(0);
    }

    @Override
    public void setUri(Uri uri) {

    }

    @Override
    public void start() {
        if(mPlayer != null){
            mPlayer.start();
        }
    }

    @Override
    public void pause() {
        if(mPlayer != null) {
            mPlayer.pause();
        }
    }

    private void release(){
        if(mPlayer != null) {
            mPlayer.reset();
            mPlayer.release();
            mPlayer = null;
        }
    }

    @Override
    public void stopPlayback() {
        if(mPlayer != null){
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
    }

    @Override
    public void seekTo(int position) {
        if(mPlayer != null){
            mPlayer.seekTo(position);
        }
    }

    @Override
    public long getDuration() {
        return (mPlayer == null || mPlayer.isPlaying())
                ?0:mPlayer.getDuration();
    }

    @Override
    public long getPosition() {
        return (mPlayer == null || mPlayer.isPlaying())
                ?0:mPlayer.getCurrentPosition();
    }

    private MediaPlayer createMediaPlayer() {
        MediaPlayer mediaPlayer = new MediaPlayer();
        return mediaPlayer;
    }

    private MediaPlayer.OnPreparedListener preparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    };

    private MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
//            try {
//                if (shuffleTag == 0) {
//                    MusicBean music = mList.get(mList.indexOf(currentMusic) + 1);
//                    mp.reset();
//                    mp.setDataSource(music.data);
//                    mp.prepare();
//                    mp.start();
//                    currentMusic = music;
//                } else {
//                    Double double1 = Math.random();
//                    int random = (int) (double1 * mList.size());
//                    MusicBean music = mList.get(random);
//                    mp.reset();
//                    mp.setDataSource(music.data);
//                    mp.prepare();
//                    mp.start();
//                    currentMusic = music;
//                }
//                PlayerState = MediaPlayer_PLAY;
//                handler.sendMessage(handler.obtainMessage(0, currentMusic));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
    };
}
